# -*- coding: utf-8 -*-
from django.shortcuts import render, render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.template import RequestContext
from models import Charge
from models import Consumption
from register.models import User
from register import settings
import time
from decimal import *
from register.keystone_util import Keystone
import datetime

#充值頁面
def charge_add(req):
    return render_to_response('billing/charge.html',context_instance=RequestContext(req))
#銀聯充值
def charge_add_union(req):
    user_id = req.session['user_id'] 
    user = User.objects.get(keystone_user_id = user_id);
    currentUsername = user.username
     #充值金额
    txnAmt = req.POST.get('txnAmt')
        #admin登录查询project信息
    keyclient = Keystone()
    v_client = keyclient.admin_login()
    project = keyclient.get_tenant(v_client,user_id)
        #获取当前系统时间
    txnTime = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
        #充值状态 0_未完成；1_完成;
    orderId = 'YL'+str(time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())))
    chargeAdd = Charge.objects.create(project_id=project.id,project_name=project.name,username=currentUsername,orderId=orderId,txnAmt=txnAmt,txnTime=txnTime,status=0)
        #跳转到支付服务器
    url = settings.union_url
    return render_to_response("billing/goto.html",{'url':url,'orderId':orderId,'txnAmt':txnAmt,'txnTime':txnTime},context_instance=RequestContext(req))

#验证充值
def check_charge(req):
    orderId =req.GET.get('orderId')
    respCode = req.GET.get('respCode')
    charge =Charge.objects.filter(orderId = orderId)[0] 
    print orderId
    print charge.project_id
    if orderId is None or respCode != '00':
        return HttpResponse('bad request')
    else:
        charge.status = 1
        charge.save()
        consumption = Consumption.objects.filter(project_id = charge.project_id).order_by("-record_time")
        newRemaining_money = Decimal(0)
        consume_money = Decimal(0)-Decimal(charge.txnAmt)
        if consumption.count() > 0:
            #最新消费记录中的余额
            lastremainingMoney = consumption[0].remaining_money
            newRemaining_money = lastremainingMoney + Decimal(charge.txnAmt)
            Consumption.objects.get_or_create(project_id=charge.project_id,project_name=charge.project_name,
            remaining_money=newRemaining_money,consume_money=consume_money,lastrecord_time=datetime.datetime.now())
        else:
            newRemaining_money=Decimal(charge.txnAmt)
            Consumption.objects.get_or_create(project_id=charge.project_id,project_name=charge.project_name,
            remaining_money=newRemaining_money,consume_money=consume_money,lastrecord_time=datetime.datetime.now())
    return render_to_response('billing/charge.html',context_instance=RequestContext(req))

#列表显示充值记录
def charge_list(req):
    page = req.GET.get('page')
    charge_list = Charge.objects.all().order_by("-txnTime")
    paginator = Paginator(charge_list, settings.PAGE_ITEMS_SHOW) # Show 25 contacts per page
    try:
        contacts = paginator.page(page) 
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)     
    return render_to_response('billing/charge_list.html', {'contacts':contacts,'charge_list':charge_list}, context_instance=RequestContext(req))




